package com.youlian.utils.bitmap;

import java.io.File;

import android.content.Context;

import com.youlian.common.Config;
import com.youlian.utils.FileHelper;

/**
 * @author simon
 * @proName vipshop_1.6.0
 * @version 1.0
 * @Data 2012-11-8 下午02:54:16
 *
   <b>Comment...</b>
 */
public class FileCache {

    private File cacheDir;

    public FileCache(Context context) {
            // 如果有SD卡则在SD卡中建一个LazyList的目录存放缓存的图片
            // 没有SD卡就放在系统的缓存目录中
            if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)){
                cacheDir = new File(android.os.Environment.getExternalStorageDirectory(),Config.imagesPath);
            }else{
                cacheDir = context.getCacheDir();
            }
            if (!cacheDir.exists()){
                cacheDir.mkdirs();
            }
    }

    /**
     *
     * @param url
     * @return
     */
    public File getFile(String url) {
            // 将url的hashCode作为缓存的文件名
           try {
        	 if(!cacheDir.exists()){
                 cacheDir.mkdirs();
             }
        	 String filename = getDownfileName(url);
//             System.out.println("filename:"+filename);
             File file = new File(cacheDir, filename);
        	 if(FileHelper.isExists(file)){
        		 return file;
        	 }
		} catch (Exception e) {
			return null;
			// TODO: handle exception
		}
		return null;
    }

    public File getFileName(String url){
    	String filename = getDownfileName(url);
    	return new File(cacheDir, filename);
    }

    public String getDownfileName(String fileUrl){
		String s1 = fileUrl.substring(fileUrl.lastIndexOf('/')+1,fileUrl.length());
//		String returnUrl = s1.substring(0, s1.indexOf('.'));
		return s1;
	}

    public void clear() {
            File[] files = cacheDir.listFiles();
            if (files == null)
                    return;
            for (File f : files)
                    f.delete();
    }

}